package com.jamlu.framework.base;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.AnyRes;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.DeviceUtils;
import com.jamlu.framework.R;
import com.jamlu.framework.presenter.IBaseRxPresenter;
import com.jamlu.framework.ui.view.IBaseView;
import com.jamlu.framework.ui.widget.MyProgressDialog;
import com.jamlu.framework.utils.StatusBarUtil;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;

/**
 * Created by DMing on 2018/02/23
 */
public abstract class BaseRxActivity<T extends IBaseRxPresenter> extends AppCompatActivity implements IBaseView {

    protected T presenter;
    private int mBackIconRes = R.drawable.ic_back_white;//返回按钮图标
    protected Toolbar mToolbar;//标题栏
    private TextView mTvTitle;//标题控件
    private MyProgressDialog mProgressDialog;//加载对话框

    //根布局
    private ViewGroup mRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRootView = (ViewGroup) LayoutInflater.from(this).inflate(getBaseLayout(), ((ViewGroup) getWindow().getDecorView()), false);
        presenter = createPresenter();
        //设置内容布局
        setContentView(mRootView);
        initBaseView();
        ButterKnife.bind(this);
        initViews(savedInstanceState);
        initData();
        initEvent();
    }

    @Override
    public Context getContext() {
        return this;
    }

    /**
     * 获取基础布局
     *
     */
    protected int getBaseLayout() {
        return R.layout.layout_base;
    }

    /**
     * 初始化界面 注入布局
     *
     */
    private void initBaseView() {
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        // 是否根据手机品牌兼容状态栏字体、背景颜色
        overrideStatusBar();
        setupTitleBar(mRootView);
        //生成内容布局
        ViewStub viewStub = findViewById(R.id.vs_content);
        viewStub.setLayoutResource(getLayoutResID());
        viewStub.inflate();
    }

    /**
     * 覆盖原来状态栏的颜色
     * 更改不必调用父类
     */
    protected void overrideStatusBar(){
        setStatusBarDark(R.color.colorPrimaryDark, true);
    }

    /**
     * 覆盖默认的toolbar背景，现在只支持drawable资源
     */
    protected @DrawableRes int overrideToolbarBg(){
        return R.drawable.bg_top_menu;
    }

    /**
     * 实现setContentView()
     */
    @LayoutRes
    protected abstract int getLayoutResID();

    /**
     * 兼容状态栏字体、背景颜色
     *
     * @param colorRes     背景颜色资源id
     * @param isDarkStatus 字体是否有暗色
     */
    public void setStatusBarDark(@ColorRes int colorRes, boolean isDarkStatus) {
        //兼容状态栏字体、背景颜色
        String model = DeviceUtils.getModel();
        if (model.contains("MI")) {//小米
            StatusBarUtil.setMiuiStatusBarDarkMode(this, isDarkStatus);
            StatusBarUtil.setColor(this, ContextCompat.getColor(this, colorRes), 0);
        } else if (model.contains("MX")) {//魅族
            StatusBarUtil.setMeizuStatusBarDarkIcon(this, isDarkStatus);
            StatusBarUtil.setColor(this, ContextCompat.getColor(this, colorRes), 0);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (isDarkStatus) {
                    StatusBarUtil.setStatusBarDarkMode(this, colorRes);
                }
            } else {
                StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.color_bg_black), 0);
            }
        }
    }

    /**
     * 初始化标题栏
     *
     * @param rootView 根布局
     */
    protected void setupTitleBar(ViewGroup rootView) {
        mToolbar = rootView.findViewById(R.id.toolbar);
        mToolbar.setTitle("");
        mToolbar.setNavigationIcon(setBackIcon()); //设置返回按钮图标
        mToolbar.setBackgroundResource(overrideToolbarBg());
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            //设置返回键是否可用
            getSupportActionBar().setHomeButtonEnabled(isShowBackIcon());
            //设置返回键是否显示
            getSupportActionBar().setDisplayHomeAsUpEnabled(isShowBackIcon());
            if (isShowBackIcon()) {
                //点击返回键
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBack();
                    }
                });
            }
        }

        // 动态设置标题位置样式，默认为显示标题
        ViewStub mVsTitle = rootView.findViewById(R.id.vs_title);
        if (getTitleLayoutRes() == 0) {//默认标题布局
            mVsTitle.setLayoutResource(R.layout.layout_title_textview);
            mVsTitle.inflate();
            mTvTitle = findViewById(R.id.tv_title);
        } else {//自定义标题布局
            mVsTitle.setLayoutResource(getTitleLayoutRes());
            mVsTitle.inflate();
            mTvTitle = findViewById(R.id.tv_title);
        }
    }

    /**
     * 获取标题布局资源
     * @return 资源
     */
    public int getTitleLayoutRes() {
        return 0;
    }

    public Toolbar getToolbar() {
        return mToolbar;
    }

    /**
     * 是否显示返回按钮
     * @return 资源
     */
    protected boolean isShowBackIcon() {
        return true;
    }


    /**
     * 设置返回按钮样式
     * @return 资源
     */
    @AnyRes
    protected int setBackIcon() {
        return mBackIconRes;
    }

    /**
     *
     * 获取P层实现类
     */
    protected T getPresenter() {
        return presenter;
    }

    /**
     * 初始化P层实现类
     * @return Presenter
     */
    protected abstract T createPresenter();
    /**
     * 设置标题
     *
     * @param title 标题字符串
     */
    protected void setTitle(@NonNull String title) {
        if (mTvTitle != null) {
            mTvTitle.setText(title);
        }
    }

    /**
     * 设置标题资源文本
     *
     * @param res string文件资源字符串
     */
    public void setTitleRes(int res) {
        String title = getResources().getString(res);
        if (mTvTitle != null) {
            mTvTitle.setText(title);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void finish() {
        if (presenter != null)presenter.disposeAll();
        super.finish();
    }

    /**
     * 返回
     */
    protected void onBack() {
        onBackPressed();
    }


    /**
     * 设置editText点击外部区域时可消失
     *
     * @param ev 触摸事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    /**
     * 显示加载对话框
     * @param cancelable 是否能点击取消
     */
    @Override
    public void showProgressDialog(Dialog dialog,boolean cancelable) {
        dialog.setCancelable(cancelable);
        dialog.show();
    }

    /**
     * 隐藏加载对话框
     */
    @Override
    public void dismissProgressDialog(Dialog dialog) {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 初始化对话框
     */
    @Override
    public Dialog createNewProgressDialog() {
        mProgressDialog = new MyProgressDialog(this);
        mProgressDialog.setCanceledOnTouchOutside(false);
        return mProgressDialog;
    }

//    /**
//     * 设置右侧菜单
//     *
//     * @param menu
//     * @return
//     */
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
////        getMenuInflater().inflate(R.menu.titlebar_menu, menu);
////        menu.findItem(R.id.item2).setVisible(false);
//        return true;
//    }
//
//    /**
//     * 右侧菜单点击事件
//     *
//     * @param item
//     * @return
//     */
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
////        int itemId = item.getItemId();
////        switch (itemId) {
////            case R.id.item1:
////
////                break;
////        }
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissProgressDialog(mProgressDialog);
    }

    /**
     * 初始化布局组件
     */
    protected void initViews(Bundle savedInstanceState) {

    }

    /**
     * 初始化布局组件的数据
     */
    protected abstract void initData();

    /**
     * 初始化布局组件的监听事件
     */
    protected abstract void initEvent();

}
